import React from 'react';
import {injectIntl} from './intl';
import {Table, Affix, Alert, Row, message} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {
    PAGE,
    TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
    DATETIME_FORMAT,
    ROWSELECTION_FIXED_COLUMN_WIDTH,
} from '../constants';
import styles from './style.css';
import {Link} from 'react-router-dom';
import {hasPermissions, conventSorter, getPrintPageUrl} from './utils';
import {currency, claimSettlementBillStatus} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount, exportDownload} from '../utils';
import WrappedTag from '../common/WrappedTag';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import difference from 'lodash/difference';
import {exportPi} from './api';
export class TablePanel extends React.PureComponent {
    state = {
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
        showTags: false
    };
    handleSubmit = id => {
        this.setState({
            loading: true
        });
        this.props.onClickSubmit(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    
    handleInvoice = id => {
        this.setState({
            loading: true
        });
        const ids = [id];
        this.props.onClickInvoice(ids).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    handleReSettle = id => {
        this.setState({
            loading: true
        });
        this.props.onClickReSettlement(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    handleFinance = id => {
        this.setState({
            loading: true
        });
        this.props.onClickFinance(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    toggleShowTags = () => {
        this.setState({
            showTags: !this.state.showTags
        });
    };


    onConfirm = () => {
        if(!this.state.selectedRowKeys.length)
            return message.warn(this.props.intl.formatMessage({
                id: 'tablePanel.validate.invoice',
                defaultMessage: '需开票通知的结算单不能为空'
            }));
        this.setState({
            loading: true
        });
        this.props.onClickInvoice(this.state.selectedRowKeys).then(success => {
            if(success)
                return this.setState({
                    loading: false,
                    selectedRowKeys: [],
                    selectedRows: [],
                });
            return this.setState({
                loading: false,
            });
        });
    };

    onSelectChange = (selectedRowKeys, selectedRows) => {
        const data = this.state.selectedRows;
        const preSelectedKeys = this.state.selectedRowKeys; // 勾选行

        if(selectedRowKeys.length > preSelectedKeys.length)
            selectedRows.forEach(v => {
                if(data.findIndex(d => d.id === v.id) === -1) data.push(v);
            });
        else {
            // 取消勾选
            const diffKeys = difference(preSelectedKeys, selectedRowKeys);
            diffKeys.forEach(k => {
                const index = data.findIndex(d => d.id === k);
                data.splice(index, 1);
            });
        }
        this.setState({
            selectedRowKeys,
            selectedRows: data
        });
    };

    onClearAll = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: [],
        });
        this.props.onChangeBatch();
    };

    onDelete = id => {
        const keys = this.state.selectedRowKeys.filter(k => k !== id);
        const rows = this.state.selectedRows.filter(r => r.id !== id);
        this.setState({
            selectedRowKeys: [...keys],
            selectedRows: [...rows]
        });
    };

    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE.index});
    };

    onPrint = e => {
        e.stopPropagation();
        const {id} = e.target.dataset;
        window.open(getPrintPageUrl(id, this.props.currentUserName));
    }
    onExportPi = e => {
        this.setState({loading: true});
        const {id} = e.target.dataset;
        exportPi(id)
            .then(res => {
                this.setState({loading: false});
                exportDownload(res.data);
            });
    }
    onClickApprove = e => {
        const {id} = e.target.dataset;
        const record = this.props.data.find(d => d.id === id);
        if(!record.isApprove)
            return message.warn(this.props.intl.formatMessage({
                id: 'tablePanel.message.isApprove',
                defaultMessage: '当前登录人员，不在审核序列中'
            }));
        this.props.history.push(routes.moreApprove.format(id));
    }
    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '结算单号'
                }),
                dataIndex: 'code',
                sorter: true,
                render: (text, record) => this.props.isBatch ? text : (
                    <Link key="detail" to={routes.detail.format(record.id)}>
                        {text}
                    </Link>
                )
            },
            {

                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brand',
                    defaultMessage: '品牌'
                }),
                sorter: true,
                dataIndex: 'brandCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.tradeMethodName',
                    defaultMessage: '贸易方式'
                }),
                dataIndex: 'tradeMethodName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                render: text => conventEnumValueToString(claimSettlementBillStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.currency',
                    defaultMessage: ' 币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.creatorTime',
                    defaultMessage: '预结算日期'
                }),
                dataIndex: 'createTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.invoiceNotificationTime',
                    defaultMessage: '结算日期'
                }),
                dataIndex: 'invoiceNotificationTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.uploadTime',
                    defaultMessage: '上传PI时间'
                }),
                dataIndex: 'uploadTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }
        ];
        if(!this.props.isMoneyVisible)
            columns.splice(1, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.materialFee',
                        defaultMessage: '材料费'
                    }),
                    dataIndex: 'materialFee',
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.mgmtFee',
                        defaultMessage: '配件管理费'
                    }),
                    dataIndex: 'mgmtFee',
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.laborFee',
                        defaultMessage: '工时费'
                    }),
                    dataIndex: 'laborFee',
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.suppleMaterialFee',
                        defaultMessage: '辅料费'
                    }),
                    dataIndex: 'suppleMaterialFee',
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.totalFee',
                        defaultMessage: '费用合计'
                    }),
                    dataIndex: 'totalFee',
                    sorter: true,
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                });
        
        const otherColums = [];
        if(!this.props.isDealerUser)
            otherColums.push(
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代号'
                    }),
                    sorter: true,
                    dataIndex: 'dealerCode'
                });
        columns.splice(1, 6, ...otherColums);
        let rowSelection = null;
        if(this.props.isBatch)
            rowSelection = {
                fixed: true,
                columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
                type: 'checkbox',
                getCheckboxProps: record => ({
                    disabled: !hasPermissions(record.options, PERMISSION.invoice)
                }),
                selectedRowKeys: this.state.selectedRowKeys,
                onChange: this.onSelectChange
            };
        else
            columns.push(
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.action',
                        defaultMessage: '操作'
                    }),
                    dataIndex: 'action',
                    width: FIXED_COLUMN_WIDTH,
                    fixed: 'right',
                    render: (t, r) => {
                        const menus = [
                            {
                                id: PERMISSION.update,
                                children: (
                                    <Link key="update" to={routes.update.format(r.id)}>
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.update',
                                            defaultMessage: '编辑'
                                        })}
                                    </Link>
                                ),
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                            },
                            {
                                id: PERMISSION.submit,
                                children: ref =>
                                    <WrappedPopconfirm
                                        id={r.id}
                                        key="abandon"
                                        title={this.props.intl.formatMessage({
                                            id: 'tablePanel.popconfirm.message',
                                            defaultMessage: '是否继续?'
                                        })}
                                        onVisibleChange={ref.setMenuVisible}
                                        onConfirm={this.handleSubmit}>
                                        <a key="submit">
                                            {this.props.intl.formatMessage({
                                                id: 'tablePanel.operation.submit',
                                                defaultMessage: '提交'
                                            })}
                                        </a>
                                    </WrappedPopconfirm>,
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(r.options, PERMISSION.submit))
                            },
                            {
                                id: PERMISSION.approve,
                                children: (
                                    <Link key="approve" to={routes.approve.format(r.id)}>
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.approve',
                                            defaultMessage: '财务审核'
                                        })}
                                    </Link>
                                ),
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve))
                            },

                            {
                                id: PERMISSION.invoice,
                                children: ref =>
                                    <WrappedPopconfirm
                                        id={r.id}
                                        key="invoice"
                                        title={this.props.intl.formatMessage({
                                            id: 'tablePanel.popconfirm.message',
                                            defaultMessage: '是否继续?'
                                        })}
                                        onVisibleChange={ref.setMenuVisible}
                                        onConfirm={this.handleInvoice}>
                                        <a key="invoice">
                                            {this.props.intl.formatMessage({
                                                id: 'tablePanel.operation.invoice',
                                                defaultMessage: '开票通知'
                                            })}
                                        </a>
                                    </WrappedPopconfirm>,
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.invoice) && hasPermissions(r.options, PERMISSION.invoice))
                            },
                            {
                                id: PERMISSION.finance,
                                children: ref =>
                                    <WrappedPopconfirm
                                        id={r.id}
                                        key="finance"
                                        title={this.props.intl.formatMessage({
                                            id: 'tablePanel.popconfirm.message',
                                            defaultMessage: '是否继续?'
                                        })}
                                        onVisibleChange={ref.setMenuVisible}
                                        onConfirm={this.handleFinance}>
                                        <a key="finance">
                                            {this.props.intl.formatMessage({
                                                id: 'tablePanel.operation.finance',
                                                defaultMessage: '上报财务'
                                            })}
                                        </a>
                                    </WrappedPopconfirm>,
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.finance) && hasPermissions(r.options, PERMISSION.finance))
                            },
                            {
                                id: PERMISSION.confirmPI,
                                children: (
                                    <Link key="confirmPI" to={routes.confirmPI.format(r.id)}>
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.confirmPI',
                                            defaultMessage: '确认PI'
                                        })}
                                    </Link>
                                ),
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.confirmPI) && hasPermissions(r.options, PERMISSION.confirmPI))
                            },
                            {
                                id: PERMISSION.reSettlement,
                                children: ref =>
                                    <WrappedPopconfirm
                                        id={r.id}
                                        key="reSettlement"
                                        title={this.props.intl.formatMessage({
                                            id: 'tablePanel.popconfirm.message',
                                            defaultMessage: '是否继续?'
                                        })}
                                        onVisibleChange={ref.setMenuVisible}
                                        onConfirm={this.handleReSettle}>
                                        <a key="reSettlement">
                                            {this.props.intl.formatMessage({
                                                id: 'tablePanel.operation.reSettlement',
                                                defaultMessage: '反结算'
                                            })}
                                        </a>
                                    </WrappedPopconfirm>,
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.reSettlement) && hasPermissions(r.options, PERMISSION.reSettlement))
                            },
                            {
                                id: PERMISSION.abandon,
                                children: ref =>
                                    <WrappedPopconfirm
                                        id={r.id}
                                        key="abandon"
                                        title={this.props.intl.formatMessage({
                                            id: 'tablePanel.popconfirm.message',
                                            defaultMessage: '是否继续?'
                                        })}
                                        onVisibleChange={ref.setMenuVisible}
                                        onConfirm={this.handleAbandon}>
                                        <a key="abandon">
                                            {this.props.intl.formatMessage({
                                                id: 'tablePanel.operation.abandon',
                                                defaultMessage: '作废'
                                            })}
                                        </a>
                                    </WrappedPopconfirm>,
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                            },
                            {
                                id: PERMISSION.export,
                                children: (
                                    <a key="export" onClick={this.onPrint} data-id={r.id}>
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.export',
                                            defaultMessage: '导出'
                                        })}
                                    </a>
                                ),
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.export) && hasPermissions(r.options, PERMISSION.export))
                            },
                            {
                                id: PERMISSION.exportPi,
                                children: (
                                    <a key="exportPi" onClick={this.onExportPi} data-id={r.id}>
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.exportPi',
                                            defaultMessage: '导出PI'
                                        })}
                                    </a>
                                ),
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.exportPi) && hasPermissions(r.options, PERMISSION.exportPi))
                            },
                            {
                                id: PERMISSION.upPi,
                                children: (
                                    <Link key="upPi" to={routes.upPi.format(r.id)}>
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.upPi',
                                            defaultMessage: '上传PI'
                                        })}
                                    </Link>
                                ),
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.upPi) && hasPermissions(r.options, PERMISSION.upPi))
                            }, {
                                id: PERMISSION.moreApprove,
                                children: <a key="moreApprove" data-id={r.id} onClick={this.onClickApprove}>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.moreApprove',
                                        defaultMessage: '审核'
                                    })
                                }</a>,
                                hidden: !(hasPermissions(this.props.permissions, PERMISSION.moreApprove) && hasPermissions(r.options, PERMISSION.moreApprove)),
                            }
                        ];
                        return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                    }
                }
            );
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };

        const alertMessage = (
            <div>
                <span>
                    {this.props.intl.formatMessage({
                        id: 'tablePanel.alertMessage.span',
                        defaultMessage: '已选择'
                    })}
                    <a onClick={this.toggleShowTags}>
                        {this.state.selectedRows.length}
                        {this.props.intl.formatMessage({
                            id: 'tablePanel.alertMessage.a.number',
                            defaultMessage: '项'
                        })}
                    </a>
                    {this.props.intl.formatMessage({
                        id: 'tablePanel.alertMessage.comma',
                        defaultMessage: '，'
                    })}
                    {this.props.intl.formatMessage({
                        id: 'tablePanel.alertMessage.assignText',
                        defaultMessage: '可进行'
                    })}
                    <a
                        size="small"
                        type="primary"
                        onClick={this.onConfirm}>
                        {this.props.intl.formatMessage({
                            id: 'tablePanel.btn.closeBtn',
                            defaultMessage: '批量开票'
                        })}
                    </a>
                </span>
                {this.state.showTags && (
                    <div className={styles.partTag}>
                        {this.state.selectedRows.map(r => (
                            <WrappedTag key={r.id} closable id={r.id} onClose={this.onDelete}>
                                {r.code}
                            </WrappedTag>
                        ))}
                    </div>
                )}
            </div>
        );
        return (
            <div>
                {this.props.isBatch && <Affix offsetTop={0} className={styles.alertMargin}><Row>
                    <Alert message={alertMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{this.props.intl.formatMessage({
                            id: 'tablePanel.warning.closeText',
                            defaultMessage: '退出'
                        })}</span>} onClose={this.onClearAll} />
                </Row></Affix>}
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    rowSelection={rowSelection}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
            </div>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeBatch: PropTypes.func.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickFinance: PropTypes.func.isRequired,
    onClickInvoice: PropTypes.func.isRequired,
    onClickReSettlement: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isMoneyVisible: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
import {
    tableSearch,
    exportData,
    onClickAbandon,
    onClickSubmit,
    onClickReSettlement,
    onClickInvoice,
    onClickFinance,
    changeBatch,
} from './actions';
const EMPTY_ARRAY = [];
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        }));
    }
);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    currentUserName: state.getIn(['page', 'domainData', 'initData', 'currentUserName']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state),
    brands: getBrandsData(state),
    isBatch: state.getIn(['page', 'appState', 'isBatch']),
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickExport: () => dispatch(exportData()),
    onClickAbandon: id =>
        dispatch(onClickAbandon(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickSubmit: id =>
        dispatch(onClickSubmit(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickInvoice: ids =>
        dispatch(onClickInvoice(ids)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickFinance: id =>
        dispatch(onClickFinance(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickReSettlement: id =>
        dispatch(onClickReSettlement(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onChangeBatch: () => dispatch(changeBatch()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(TablePanel));
